/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var async  = require( 'async'); // 同步控制


// Schema 结构
var YjxCustAnimationModel = function(obj){
    YjxBaseModel.call(this,obj);

    // 以下为表定义数据，需要的字段就填入
    //`ani_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '动画ID',
    //`ani_type` int(2) NOT NULL DEFAULT '0' COMMENT '0未知, 10:AE, 20:C4D',
    //`use` int(2) NOT NULL DEFAULT '10' COMMENT '用途：10视频模版用, 20转场效果用',
    //`private` int(1) NOT NULL DEFAULT '0' COMMENT '1私有的; 0共通的',
    //`user_type` int(1) NOT NULL DEFAULT '1' COMMENT '用户类型: 0:未知, 10:内部人员, 20:普通用户',
    //`user_id` bigint(20) NOT NULL COMMENT '用户ID',
    //`ani_name` varchar(100) NOT NULL DEFAULT '' COMMENT '自定义动画名称',
    //`tmpl_json` mediumtext COMMENT 'bodymovin导出的json模版',
    //`tmpl_set` mediumtext COMMENT '模版的默认设置',
    //`tmpl_para` mediumtext COMMENT '模版的可修改参数',
    //`url` varchar(1000) DEFAULT '' COMMENT '预览用视频URL地址(完整视频mp4)',
    //`thumb_v` varchar(1000) DEFAULT NULL COMMENT '预览用视频URL地址(抽帧的mp4或gif)',
    //`thumbs` text COMMENT '预览用缩略图',
    //`duration` float NOT NULL DEFAULT '0' COMMENT '播放时长，单位秒',
    //`size_id` bigint(20) NOT NULL COMMENT '尺寸id（和vedio_design_doc.size_id匹配）',
    //`create_time` datetime NOT NULL,
    //`update_time` datetime NOT NULL,
    //`update_by` varchar(50) NOT NULL DEFAULT '',
    //`del_flg` int(1) NOT NULL DEFAULT '0',

};

YjxCustAnimationModel.prototype = new YjxBaseModel();

// 取得表名
YjxCustAnimationModel.prototype.getTableName = function(){
    return 'yjx_cust_animation';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxCustAnimationModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'ani_id='+this.ani_id;
};


// ids 数组
YjxCustAnimationModel.prototype.getCustAniListByIds = function(arrIds,callback){
    var THIS = this;

    if(!arrIds||arrIds.length==0) {
        return callback(null, null);
    }

    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var ids = arrIds.join(',');
        var sql = 'SELECT t.* FROM yjx.yjx_cust_animation t '+
                ' WHERE t.del_flg=0 AND t.ani_id IN ('+ids+') '+
                ' ORDER BY t.ani_id ';
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });
    });
};

/**
 * 获取自定义动画列表
 * @param userId[可选]: 按用户查找
 * @param type: 10:AE, 20:C4D, 其他:全部
 * @param sizeId: 匹配指定视频尺寸
 * @param use(用途): 10视频模版用, 20转场效果用
 * @param pageNum
 * @param pageSize
 * @param callback
 */
function sql_getCustAniBySize(bForCnt, userId, aniType, sizeId, use, pageNum, pageSize) {
    var sql = '';
    if(bForCnt) {
        sql += ' SELECT count(*) AS cnt ';
    } else {
        sql += ' SELECT t.* ';
    }
    sql += ' FROM yjx.yjx_cust_animation t '+
        ' WHERE t.del_flg=0 AND t.size_id='+sizeId;
    if(Number(userId||'0')>0) {
        sql += ' AND ( (t.user_id='+userId+ ' AND t.private=1) OR (t.private=0) ) ';
    } else {
        sql += ' AND t.private=0 ';
    }
    if(Number(aniType||'0')>0) {
        sql += ' AND t.ani_type='+aniType;
    }
    if(Number(use||'0')>0) {
        sql += ' AND t.use='+use;
    }

    if(!bForCnt) {
        sql += ' ORDER BY t.update_time DESC, t.ani_id DESC ';

        if(typeof pageNum!='undefined' && pageNum != null && typeof pageSize!='undefined' && pageSize != null){
            var skipCnt = Number(pageNum)*Number(pageSize);
            sql += " LIMIT " + skipCnt + "," + Number(pageSize);
        }
    }

    return sql;
}

/**
 * 获取自定义动画列表
 * @param userId[可选]: 按用户查找
 * @param type: 10:AE, 20:C4D, 其他:全部
 * @param sizeId: 匹配指定视频尺寸
 * @param use(用途): 10视频模版用, 20转场效果用
 * @param pageNum
 * @param pageSize
 * @param callback
 */
YjxCustAnimationModel.prototype.getCustAniListBySize = function(userId,aniType,sizeId,use,pageNum,pageSize,callback){
    var THIS = this;
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = sql_getCustAniBySize(false, userId, aniType, sizeId, use, pageNum, pageSize);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });
    });
};
YjxCustAnimationModel.prototype.getCustAniListBySizeCnt = function(userId, aniType, sizeId, use, callback){
    var THIS = this;
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = sql_getCustAniBySize(true, userId, aniType, sizeId, use);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            var total=0;
            if(error) {
                console.log(error);
            } else if (items) {
                console.log('find item');
                total = items[0].cnt;
            } else{
                console.log('find no one');
            }
            // 回调
            callback(error, total);
        });
    });
};

/**
 * 逻辑删除
 * @param userId
 * @param aniId
 * @param callback
 */
YjxCustAnimationModel.prototype.logicDelCustAniByUser = function(userId,aniId,callback){

    var THIS = this;

    //mysql update
    pool.pool.getConnection(function(err, connection) {
        // Use the connection

        var sql = 'UPDATE yjx.yjx_cust_animation '+
            ' SET del_flg=1, update_time=sysdate(), update_by='+userId+
            ' WHERE ani_id='+aniId+' AND user_id='+userId;

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error) {
                console.log('YjxCustAnimationModel.logicDelCustAniByUser Err:'+error);
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 根据video_design_doc的cust_ani_ids来查找自定义动画
 * @param custAniIds，例如：'[34,35]'
 * @param callback,参数如下：
 *              error:
 *              data:[如果有自定义动画，必需]自定义动画的dbId和tmpl_json的map的json，例如 '{"1":{}, "2":{}}'
 *                  如果没有自定义动画，则返回空字符串
 */
YjxCustAnimationModel.prototype.findCustAnisFromDB = function(custAniIds,callback){
    if(!custAniIds || custAniIds.length<=2){
        return callback(null, "");
    }
    custAniIds = custAniIds.substring(1, custAniIds.length-1);

    var THIS = this;

    //mysql update
    pool.pool.getConnection(function(err, connection) {
        // Use the connection

        var sql = ' select a.ani_id, a.tmpl_json '+
        ' from yjx.`yjx_cust_animation` a '+
        ' where  a.`ani_id` in ( '+custAniIds +' ) ';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error ) {
                console.log('YjxCustAnimationModel.findCustAnisFromDB Err:'+error);
                callback(error);
            } else if(!result ||result.length==0) {
                //

                callback(null,"");
            }else{
                var data={};
                for(var i=0;i<result.length;i++){
                    var one =  result[i];
                    data[one.ani_id] = JSON.parse(one.tmpl_json);
                }
                callback(null, JSON.stringify(data));
            }
        });
    });
};




/**
 * 获取转场ids
 * @param callback,参数如下：
 *              error:
 *
 */
YjxCustAnimationModel.prototype.findAnimationIds = function (callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActivityModel.js [findAnimationIds] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = "SELECT	" +
            "     vdd.design_id,  "+
            "     vdd.design_name AS `name`,  "+
            "     IFNULL(vdd.theme_thumb,'') AS icon,  "+
            "	  vdd.cust_ani_ids AS anIds	" +
            "	FROM	" +
            "	  yjx.yjx_uni_items yui,	" +
            "	  yjx.yjx_tmpl_set_r ytsr,	" +
            "	  yjx.yjx_tmpl_set yts,	" +
            "	  itbour.video_design_doc vdd	" +
            "	WHERE yts.use = 20	" +
            "	AND yts.publish = 1	" +
            "	AND yui.uni_item_id = ytsr.uni_item_id	" +
            "	AND ytsr.set_id = yts.set_id	" +
            "	AND yui.item_id = vdd.design_id	" +
            "	AND yui.del_flg = 0	" +
            "	AND ytsr.del_flg = 0	" +
            "	AND yts.del_flg = 0	" +
            "	AND vdd.del_flg = 0	" ;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};


/**
 * 获取转场的信息
 * @param anId 转场id
 * @param callback,参数如下：
 *              error:
 *
 */
YjxCustAnimationModel.prototype.getAnimationInfo = function(anId,callback){
    //mysql update
    pool.pool.getConnection(function(err, connection) {
        // Use the connection

        var sql ="	SELECT	" +
                "	  yca.ani_id AS id ,	" +
                "	  yca.ani_name AS `name`,	" +
                "	  IFNULL(yca.thumb_v,'') AS icon,	" +
                "	  yca.tmpl_set	" +
                "	FROM	" +
                "	  yjx.yjx_cust_animation yca	" +
                "	WHERE yca.ani_id = "+anId+"	" +
                "	AND yca.use = 20	";
                // "	AND yca.del_flg = 0	" ;  巨坑!!!!;  此表的 del_flg 标记无效, 即使 del_flg 为1 的也认定有效
            console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error ) {
                console.log('YjxCustAnimationModel.findAnimationIds Err:'+error);
                callback(error);
            }

            callback(null, result);

        });
    });
};



// 导出
module.exports = YjxCustAnimationModel;